<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>DeepSeek 流式聊天</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* 同上 */
    </style>
</head>
<body>
<div class="chat-container">
    <h1 class="text-center mb-4">DeepSeek 流式聊天</h1>

    <div id="chat-messages">
        <!-- 历史消息 -->
        <div th:each="message : ${messages}"
             th:classappend="${message.role == 'user' ? 'user-message' : 'assistant-message'}"
             class="message">
            <strong th:text="${message.role == 'user' ? '你' : 'DeepSeek'}"></strong>:
            <div th:text="${message.content}"></div>
        </div>

        <!-- 流式响应容器 -->
        <div id="streaming-response" class="message assistant-message" style="display: none;">
            <strong>DeepSeek</strong>:
            <div id="response-content"></div>
        </div>
    </div>

    <form id="chat-form" class="mt-4">
        <div class="input-group">
            <input type="text" id="user-input"
                   class="form-control" placeholder="输入你的消息..." required>
            <button type="submit" class="btn btn-primary">发送</button>
        </div>
    </form>
</div>

<script>
    document.getElementById('chat-form').addEventListener('submit', function(e) {
        e.preventDefault();
        const input = document.getElementById('user-input');
        const message = input.value.trim();

        if (message) {
            // 显示用户消息
            const chatMessages = document.getElementById('chat-messages');
            const userMessage = document.createElement('div');
            userMessage.className = 'message user-message';
            userMessage.innerHTML = `<strong>你</strong>:<div>${message}</div>`;
            chatMessages.appendChild(userMessage);

            // 准备AI响应区域
            const streamingDiv = document.getElementById('streaming-response');
            const responseContent = document.getElementById('response-content');
            streamingDiv.style.display = 'block';
            responseContent.textContent = '';

            // 发送请求
            const eventSource = new EventSource(`/send-stream?message=${encodeURIComponent(message)}`);

            eventSource.onmessage = function(e) {
                responseContent.textContent += e.data;
            };

            eventSource.onerror = function() {
                eventSource.close();
                streamingDiv.style.display = 'none';
                // 将完整响应添加到历史记录
                const assistantMessage = document.createElement('div');
                assistantMessage.className = 'message assistant-message';
                assistantMessage.innerHTML = `<strong>DeepSeek</strong>:<div>${responseContent.textContent}</div>`;
                chatMessages.appendChild(assistantMessage);
            };

            input.value = '';
        }
    });
</script>
</body>
</html>